from rest_framework import serializers
from rest_framework.response import Response
from django.db import transaction

from goods.models import SKU, GoodsCategory, SPUSpecification, SpecificationOption, SKUSpecification


class SKUSpecificationSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ('spec_id', 'option_id')


# sku表的序列化器
class SkusSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)

    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    specs = SKUSpecificationSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    def create(self, validated_data):
        specs = validated_data['specs']
        del validated_data['specs']
        # 开启事务
        with transaction.atomic():
            # 设置保存点
            save = transaction.savepoint()
            try:
                sku = super().create(validated_data)

                for spec in specs:
                    SKUSpecification.objects.create(sku=sku, option_id=spec['option_id'], spec_id=spec['spec_id'])
            except:
                # 如果失败则回滚
                transaction.savepoint_rollback(save)
                raise serializers.ValidationError('保存失败')
            else:
                # 成功则提交
                transaction.savepoint_commit(save)

                return sku

    def update(self, instance, validated_data):

        specs = validated_data['specs']

        del validated_data['specs']
        # 开启事务
        with transaction.atomic():
            # 设置保存点
            save = transaction.savepoint()
            try:
                sku = super().update(instance, validated_data)

                for spec in specs:
                    SKUSpecification.objects.create(sku=sku, option_id=spec['option_id'], spec_id=spec['spec_id'])
            except:
                # 如果失败则回滚
                transaction.savepoint_rollback(save)
                raise serializers.ValidationError('保存失败')
            else:
                # 成功则提交
                transaction.savepoint_commit(save)
                return sku


class GoodsCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


# 规格选项表的序列化器
class SpecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ('id', 'value')


# 规格表序列化器
class SPUSpecificationSerializer(serializers.ModelSerializer):
    # 子表嵌套父表的字段
    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()
    # 具体规格选项   父表嵌套字表的字段
    options = SpecificationOptionSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = '__all__'
